package com.benshou.bcss.common.db.mybatisplus.config;

import com.baomidou.mybatisplus.annotation.DbType;
import com.baomidou.mybatisplus.autoconfigure.ConfigurationCustomizer;
import com.baomidou.mybatisplus.core.incrementer.DefaultIdentifierGenerator;
import com.baomidou.mybatisplus.core.incrementer.IdentifierGenerator;
import com.baomidou.mybatisplus.extension.plugins.MybatisPlusInterceptor;
import com.baomidou.mybatisplus.extension.plugins.inner.OptimisticLockerInnerInterceptor;
import com.baomidou.mybatisplus.extension.plugins.inner.PaginationInnerInterceptor;
import com.baomidou.mybatisplus.extension.plugins.inner.TenantLineInnerInterceptor;
import com.benshou.bcss.common.db.mybatisplus.TenantLineHandlerImpl;
import com.benshou.bcss.common.db.mybatisplus.typehandler.JacksonJsonTypeHandlerFactory;
import com.benshou.bcss.common.db.mybatisplus.typehandler.TypeHandlerRegister;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.List;

/**
 * MyBatis-Plus 相关配置
 *
 * @author <a href="mailto:liuzhenbang@benshou.com">Liu Zhenbang</a>
 */
@Configuration
public class MyBatisPlusConfig {

    /**
     * @return Id 生成器
     */
    @Bean
    public IdentifierGenerator identifierGenerator() {
        return DefaultIdentifierGenerator.getInstance();
    }

    /**
     * @return MyBatis-Plus 拦截器
     */
    @Bean
    public MybatisPlusInterceptor mybatisPlusInterceptor() {
        var interceptor = new MybatisPlusInterceptor();
        // 多租户
        interceptor.addInnerInterceptor(new TenantLineInnerInterceptor(new TenantLineHandlerImpl()));
        // version 乐观锁
        interceptor.addInnerInterceptor(new OptimisticLockerInnerInterceptor());
        // 分页
        interceptor.addInnerInterceptor(new PaginationInnerInterceptor(DbType.MYSQL));
        return interceptor;
    }

    /**
     * @param objectMapper 对象映射实例
     * @return Jackson Json 的 TypeHandler 工厂
     */
    @Bean
    public JacksonJsonTypeHandlerFactory jacksonJsonTypeHandlerFactory(ObjectMapper objectMapper) {
        return new JacksonJsonTypeHandlerFactory(objectMapper);
    }

    /**
     * @param typeHandlerRegisters 列表：TypeHandler 注册器
     * @return MyBatis-Plus 自定义配置
     */
    @Bean
    public ConfigurationCustomizer configurationCustomizer(List<TypeHandlerRegister<?>> typeHandlerRegisters) {
        return configuration -> {
            var registry = configuration.getTypeHandlerRegistry();
            for (var register : typeHandlerRegisters) {
                register.register(registry);
            }
        };
    }
}
